package com.example.demo.zaqizabatest.多线程相关;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName 售票
 * @Author lys4134
 * @Date 2021/08/27 09:45:59
 * @Description 售票 1.三个售票窗口同时出售20张票
 * @Version 1.0
 **/
@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public class 售票 {
    private static volatile int tickets = 20;
    private static Object object = new Object();
    private static  void sellTicket() throws InterruptedException {
        while (tickets > 0) {
            synchronized(object){

                String name = Thread.currentThread().getName();
                if (tickets <= 0) {
                    System.out.println("售票窗口" + name + ",无票");
                    return;
                }
                tickets--;
                System.out.println("售票窗口" + name + "出售了一张票,剩余" + tickets + "张票");
            }
            Thread.sleep(100);
        }
    }

    public static void main(String[] args) {
        List<Thread> threads = new ArrayList<>();
        for (int i = 1; i < 4; i++) {
            threads.add(new Thread(() -> {
                try {
                    sellTicket();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, "" + i));
        }
        for (Thread thread : threads) {
            thread.start();
        }
    }
}
